import { Word, UserProgress } from '../models/word';
import { Category } from '../models/category';
import dataPreferences from '@ohos.data.preferences';
import common from '@ohos.app.ability.common';

// 获取应用全局上下文（需要在应用启动时设置）
let applicationContext: common.Context | null = null;

// 设置应用上下文的函数（需要在应用入口处调用）
export function setApplicationContext(context: common.Context) {
  applicationContext = context;
}

class StorageService {
  private static instance: StorageService;
  private wordsKey = 'words_data';
  private progressKey = 'user_progress';
  private categoriesKey = 'categories_data';
  private preferenceName = 'not_memorizing_vocabulary_data';

  private constructor() {}

  static getInstance(): StorageService {
    if (!StorageService.instance) {
      StorageService.instance = new StorageService();
    }
    return StorageService.instance;
  }

  // 确保应用上下文已设置
  private checkContext(): common.Context {
    if (!applicationContext) {
      throw new Error('Application context is not set. Please call setApplicationContext() first.');
    }
    return applicationContext;
  }

  // 获取所有单词
  async getWords(): Promise<Word[]> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      const data = await prefs.get(this.wordsKey, '[]');
      return JSON.parse(data as string) as Word[];
    } catch (error) {
      console.error('Failed to get words:', error);
      return [];
    }
  }

  // 保存单词
  async saveWords(words: Word[]): Promise<void> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      await prefs.put(this.wordsKey, JSON.stringify(words));
      await prefs.flush();
    } catch (error) {
      console.error('Failed to save words:', error);
    }
  }

  // 获取用户进度
  async getUserProgress(): Promise<UserProgress> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      const data = await prefs.get(this.progressKey, JSON.stringify(this.getDefaultProgress()));
      return JSON.parse(data as string) as UserProgress;
    } catch (error) {
      console.error('Failed to get user progress:', error);
      return this.getDefaultProgress();
    }
  }

  // 保存用户进度
  async saveUserProgress(progress: UserProgress): Promise<void> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      await prefs.put(this.progressKey, JSON.stringify(progress));
      await prefs.flush();
    } catch (error) {
      console.error('Failed to save user progress:', error);
    }
  }

  // 获取分类
  async getCategories(): Promise<Category[]> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      const data = await prefs.get(this.categoriesKey, '[]');
      return JSON.parse(data as string) as Category[];
    } catch (error) {
      console.error('Failed to get categories:', error);
      return [];
    }
  }

  // 保存分类
  async saveCategories(categories: Category[]): Promise<void> {
    try {
      const context = this.checkContext();
      const prefs = await dataPreferences.getPreferences(context, this.preferenceName);
      await prefs.put(this.categoriesKey, JSON.stringify(categories));
      await prefs.flush();
    } catch (error) {
      console.error('Failed to save categories:', error);
    }
  }

  private getDefaultProgress(): UserProgress {
    return {
      userId: 'default_user',
      masteredWords: [],
      learningWords: [],
      ignoredWords: [],
      dailyGoal: 20,
      studiedToday: 0,
      streak: 0
    };
  }
}

export default StorageService.getInstance();
